package com.lilicould.controller;

import com.lilicould.entity.*;
import com.lilicould.service.HouseService;
import com.lilicould.service.impl.HouseServiceImpl;
import com.lilicould.service.impl.RepairServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/employee/personalInfo")
public class EmployeePersonalInfoController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        HouseService houseService = new HouseServiceImpl();
        ArrayList<House> allHouses = houseService.selectAllHouses();
        EmployeeDetails employeeDetails = (EmployeeDetails) req.getSession().getAttribute("employeeDetails");
        Employee employee = employeeDetails.getEmployee();
        ArrayList<House> houses = new ArrayList<>();

        // 获取所有关于该员工的房源信息
        for (House house : allHouses) {
            if (house.getManagerId().equals(employee.getEmployeeId())) {
                houses.add(house);
            }
        }

        RepairServiceImpl repairService = new RepairServiceImpl();
        // 获取所有报修信息
        ArrayList<RepairRequest> repairRequestList = repairService.selectAllRepairRequest();
        ArrayList<RepairRequest> todoRepairRequests = new ArrayList<>();
        ArrayList<RepairRequest> repairRequests = new ArrayList<>();

        // 获取所有维修记录
        ArrayList<RepairRecord> repairRecordList = repairService.selectAllRepairRecord();

        if (repairRequestList != null){
            // 对报修单进行分类
            for (RepairRequest repairRequest : repairRequestList) {
                // 如果该报修单没有其他维修工处理，则添加到待处理列表中
                if (repairRequest.getRepairEmployeeId() == null) {
                    todoRepairRequests.add(repairRequest);
                } else if (repairRequest.getRepairEmployeeId().equals(employee.getEmployeeId())) {
                    // 如果该报修单被该员工处理，则添加到列表中
                    repairRequests.add(repairRequest);
                }
            }
        }

        // 添加到域对象中
        req.getSession().setAttribute("todoRepairRequests", todoRepairRequests);
        req.getSession().setAttribute("repairRequests", repairRequests);
        req.getSession().setAttribute("repairRecords", repairRecordList);
        req.getSession().setAttribute("allHouses", allHouses);
        req.getSession().setAttribute("houses", houses);


        req.getRequestDispatcher("/page/emp/index.jsp").forward(req, resp);

    }
}
